/**
 * 
 *  @project Air Traff Monitor
 * 
 *  @author M.Emre ATASEVER <m.emre.atas@gmail.com>
 *  @author M.Burak ALKAN <mburakalkan@gmail.com>
 *  @author H.Burak KARAMIK <bkaramik@gmail.com>
 *
 *	`Air Traffic Monitor' is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "kisfilter.h"


KismetSortFilterProxy::KismetSortFilterProxy()
{
	binv	= false;
	mode	= Contains;
	bcas	= false;
	setFilterCaseSensitivity(Qt::CaseInsensitive);
}

void KismetSortFilterProxy::setInvert(bool inv)
{
	if(binv != inv)
	{
		binv	= inv;
		invalidateFilter();
	}
}

void KismetSortFilterProxy::setMode(filterMode mod)
{
	if(mode	!= mod)
	{	
		mode	= mod;
		invalidateFilter();
	}
}

void KismetSortFilterProxy::setCaseSensitive(bool cas)
{
	if(bcas != cas)
	{
		bcas	= cas;
		setFilterCaseSensitivity((bcas) ? Qt::CaseSensitive : Qt::CaseInsensitive);
		invalidateFilter();
	}
}
void KismetSortFilterProxy::setFilterString(const QString& str)
{
	if(str != strexp)
	{
		strexp	= str;
		if(mode == RegExp)
			setFilterRegExp(strexp);
		else
			invalidateFilter();
	}
}

bool KismetSortFilterProxy::checkStarts(const QString &s)
{
	return s.startsWith(strexp,filterCaseSensitivity());
}
bool KismetSortFilterProxy::checkEnds(const QString &s)
{
	return s.endsWith(strexp,filterCaseSensitivity());
}
bool KismetSortFilterProxy::checkEq(const QString &s)
{
	return (s.compare(strexp,filterCaseSensitivity()) == 0);
}
bool KismetSortFilterProxy::checkRegExp(const QString &s)
{
	return s.contains(filterRegExp());
}
bool KismetSortFilterProxy::checkContains(const QString &s)
{
	return s.contains(strexp,filterCaseSensitivity ());
}
bool KismetSortFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
	if(strexp == "")
		return true;
	QModelIndex index;
	int j		= sourceModel()->columnCount();
	bool acc	= false;

        bool (KismetSortFilterProxy::*func)(const QString&);
	
	switch(mode)
	{
		case Contains:
			func	= &KismetSortFilterProxy::checkContains;
			break;
		case Starts:
			func	= &KismetSortFilterProxy::checkStarts;
			break;
		case Ends:
			func	= &KismetSortFilterProxy::checkEnds;
			break;
		case Equals:
			func	= &KismetSortFilterProxy::checkEq;
			break;
		default:
			func	= &KismetSortFilterProxy::checkRegExp;
	}

	for(int i = 0; i < j;i++)
	{
		index	= sourceModel()->index(sourceRow,i,sourceParent);
		if((const_cast<KismetSortFilterProxy*>(this)->*func)(sourceModel()->data(index).toString()))
		{
			acc	= true;
			break;
		}
	}
	
	return (binv) ? !acc : acc;
}
